﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace KickStart.Helpers
{
    public static class ModelStateExtensions
    {
        public static List<JsonError> ToJson(this ModelStateDictionary modelState)
        {
            var errors = modelState.Select(
                ms => new JsonError
                          {
                              key = ms.Key,
                              errors = ms.Value.Errors.Select(error => (error.Exception == null)
                                                                           ?
                                                                               error.ErrorMessage
                                                                           : error.Exception.Message)
                                                        .Where(error => !string.IsNullOrEmpty(error))
                                                        .ToList()

                          }
                ).Where(ms => ms.errors.Count() > 0)
                .ToList();

            return errors;
        }
    }

    public class JsonError
    {
        public string key { get; set; }
        [XmlArray(ElementName = "messages")]
        [XmlArrayItem(ElementName = "message")]
        public List<string> errors { get; set; }
    }
}